package db

import (
	"encoding/json"
	log "github.com/sirupsen/logrus"
	"src/db/db_modle"
	"src/error_msg"
	"src/modle"
	"src/tools"
	"strings"
	"time"
)

// 获取用户info
func GetLastUsersDetails(uid uint) (db_modle.UserDetails, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error())
		return db_modle.UserDetails{}, ne
	}
	return user, nil
}

// days天内联系紧急联系人次数
func GetTouchTimesOfUrgentContacts(uid uint, days int64, logId string) (int, error) {
	var count int
	ud, e := GetLastUsersDetails(uid)
	if e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}
	var cr []modle.CallRecord
	if e := json.Unmarshal([]byte(ud.CallRecords), &cr); e != nil {
		ne := error_msg.DBJsonStrError
		log.Error(e.Error(), ne.Error(), logId)
		return 0, ne
	}
	// 紧急联系人集合
	m, e := GetUCInfo(uid)
	if e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}

	// 统计
	time := tools.GetVietnamTime().Unix() - days*60*60*24
	for k := range m {
		for _, v := range cr {
			if v.Date > time && v.Number == k {
				count ++
			}
		}
	}
	// 为获取到用户通话记录
	if count == 0 {
		ne := error_msg.ContactsNotFoundError
		log.Info(ne.Error())
		return 0, ne
	}
	return count, nil
}

// 近30天内通讯录电话通话次数
func GetNumOfCallRecordIn30Days(uid uint, days int64, logId string) (int, error) {
	var count int
	ud, e := GetLastUsersDetails(uid)
	if e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}
	var cr []modle.CallRecord
	if e := json.Unmarshal([]byte(ud.CallRecords), &cr); e != nil {
		ne := error_msg.DBJsonStrError
		log.Error(e.Error(), ne.Error(), logId)
		return 0, ne
	}
	time := tools.GetVietnamTime().Unix() - days*60*60*24
	for _, v := range cr {
		if v.Date > time {
			count ++
		}
	}
	// 如果count值为零，跳过该指标检测
	if count == 0 {
		ne := error_msg.ContactsNotFoundError
		log.Info(ne.Error())
		return 0, ne
	}
	return count, nil
}

// 获取用户最新通讯录联系人数量
func GetUsersContacts(uid uint, logId string) (int, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}
	log.println("用户通讯录数量",user.AddressBookCount)
	return user.AddressBookCount, nil
}

// 获取用户详细信息
func GetUsersDetails(uid uint) []db_modle.UserDetails {
	orm := GetMysqlOrm()
	defer orm.Close()
	var user []db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Find(&user)
	if e := result.Error; e != nil {
		log.Error(e.Error())
		return []db_modle.UserDetails{}
	}
	return user
}

// 获取用户最新通讯录联系人数量
func GetUsersLoansAppNum(uid uint, logId string) (int, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}
	return user.LoanCount, nil
}

// 获取用户最新通讯录联系人数量 0 模拟器 其他正常
func GetUsersDeviceType(uid uint, logId string) (int, error) {
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}
	deviceType := strings.ToLower(user.DeviceTypeNumber)
	if deviceType == "i386" || deviceType == "x86_64" {
		log.Infof("用户 %d 使用模拟器 %s %s", uid, deviceType, logId)
		return 0, nil
	}
	return 1, nil
}

// 获取用户最新设备号，近days天使用人数
func GetAccountNumOfSameImei(uid uint, days int, logId string) (int, error) {
	limitDay := time.Now().AddDate(0, 0, -days)
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}

	var userNum []db_modle.UserDetails
	r := orm.Raw("select * from user_details where imei_number = ? "+
		"and DATEDIFF(?,NOW()) group by user_id", user.ImeiNumber, limitDay).Find(&userNum)
	if e := r.Error; e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}
	return int(r.RowsAffected), nil
}

// 获取用户最新设备号，近days天使用人数
func GetAccountNumOfSameMac(uid uint, days int, logId string) (int, error) {
	limitDay := time.Now().AddDate(0, 0, -days)
	orm := GetMysqlOrm()
	defer orm.Close()
	var user db_modle.UserDetails
	result := orm.Where("user_id = ?", uid).Order("id desc").First(&user)
	if e := result.Error; e != nil {
		ne := error_msg.InformationNotFoundError
		log.Error(ne.Error(), logId)
		return 0, ne
	}

	var userNum []db_modle.UserDetails
	r := orm.Raw("select * from user_details where network_ip = ? "+
		"and DATEDIFF(?,NOW()) group by user_id", user.NetworkIp, limitDay).Find(&userNum)
	if e := r.Error; e != nil {
		log.Error(e.Error(), logId)
		return 0, e
	}
	return int(r.RowsAffected), nil
}
